//
//  MainMemberManagerViewController.m
//  leo
//
//  Created by RyanLin on 11/8/15.
//  Copyright © 2015 mdx. All rights reserved.
//

#import "MainMemberManagerViewController.h"

#import "AppDelegate.h"
#import "AddSafeAreaTableViewCell.h"
#import "MemberListTableCellTableViewCell.h"
#import "AddContactsViewController.h"
#import "AddSosContactsViewController.h"
#import "ModifyManagerViewController.h"
#import "InviteViewController.h"

#import "SyncManager.h"
#import "DataManager.h"
#import "LeoMsg.h"

@interface MainMemberManagerViewController ()

@property (nonatomic,retain) SyncManager *syncManager;
@property (nonatomic,retain) DataManager *dataManager;
@property (nonatomic,retain) NSArray *ContactsArray;
@property (nonatomic,retain) NSArray *ManagersArray;
@property (nonatomic,retain) NSArray *SosContactsArray;

@end


@implementation MainMemberManagerViewController

@synthesize navLeftButton;


@synthesize tableView;
@synthesize tableViewHeight;
@synthesize addSafeAreaTableViewCell;
@synthesize memberListTableCellTableViewCell;
@synthesize tableArray;
-(void)dealloc
{
    [self removeObservers];
    addSafeAreaTableViewCell=NULL;
    memberListTableCellTableViewCell=NULL;
    tableArray=NULL;
    self.syncManager=NULL;
    self.dataManager=NULL;
    self.ContactsArray=NULL;
    self.ManagersArray=NULL;
    self.SosContactsArray=NULL;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars = YES;

    [self initNavButton];
    [self initColorParam];

    [self worktable];
    
    [self initDataProxy];
    [self initData];

    
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.ManagerDetailsDataArray = [[NSMutableArray alloc]init];
    NSDictionary *dicOne = [NSDictionary dictionaryWithObjectsAndKeys:@"boy",@"avatar", @"爸爸",@"name", @"1",@"managertype", @"13602089224",@"phonenumber" ,nil];
    
    NSDictionary *dicTwo = [NSDictionary dictionaryWithObjectsAndKeys:@"girl",@"avatar", @"妈妈",@"name", @"0",@"managertype", @"13920165369",@"phonenumber" ,nil];
    [myDelegate.ManagerDetailsDataArray addObject:dicOne];
    [myDelegate.ManagerDetailsDataArray addObject:dicTwo];
    
    
    
    myDelegate.ContactsDetailsDataArray = [[NSMutableArray alloc]init];
    NSDictionary *dicOne1 = [NSDictionary dictionaryWithObjectsAndKeys:@"boy",@"avatar", @"张树华",@"name", @"13602089224",@"phonenumber" ,nil];
    
    NSDictionary *dicTwo1 = [NSDictionary dictionaryWithObjectsAndKeys:@"girl",@"avatar", @"秦泽霞",@"name", @"13920165369",@"phonenumber" ,nil];
    
    NSDictionary *dicThree = [NSDictionary dictionaryWithObjectsAndKeys:@"boy",@"avatar", @"张旭",@"name", @"15922124320",@"phonenumber" ,nil];
    
    [myDelegate.ContactsDetailsDataArray addObject:dicOne1];
    [myDelegate.ContactsDetailsDataArray addObject:dicTwo1];
    [myDelegate.ContactsDetailsDataArray addObject:dicThree];
    
    
    myDelegate.SosContactsDetailsDataArray = [[NSMutableArray alloc]init];
    
    tableArray = [[NSMutableArray alloc]init];
    //test data
    //tableArray = myDelegate.ManagerDetailsDataArray;
    
    
    tableArray = self.ManagersArray;
    NSLog(@"数量是%d",tableArray.count);
    [self registerObservers];
    // Do any additional setup after loading the view from its nib.
}

-(void)viewWillAppear:(BOOL)animated{
    //[self initData];
    //[tableView reloadData];
    /*
    UIActivityIndicatorView *loadingView=[LeoMsg showLoadingView];
    [self.view addSubview:loadingView];
    [loadingView startAnimating];
    
    User *user=[User sharedSingleton];
    NSString *userId=user.uid;
    Watch *watch=[self.dataManager getActiveWatch:userId];
    NSString *watchId=watch.deviceUid;
    
    
    [self.syncManager getBoundUsers:watchId completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        if(result==SUCESS)
        {
            [self initData];
            [tableView reloadData];
            [loadingView stopAnimating];
        }

    }];*///by yan
}

-(void)initDataProxy{
    self.syncManager=[[SyncManager alloc] init];
    self.dataManager=[[DataManager alloc] init];
}

-(void)initData{
    
//    UIActivityIndicatorView *loadingView=[LeoMsg showLoadingView];
//    [self.view addSubview:loadingView];
//    [loadingView startAnimating];
    
    User *user=[User sharedSingleton];
    NSString *userId=user.uid;

    
    Watch *watch=[self.dataManager getActiveWatch:userId];
    NSString *watchId=watch.deviceUid;

//    [self.syncManager getBoundDevices:^(SyncResult result, NSDictionary *retValue, NSString *description) {
//        if (result==YES)
//        {
//            
//            //self.ManagersArray = [self.dataManager getManagerLists:@"3" accountId:@"10"];
//            self.ManagersArray = [self.dataManager getManagerLists:watchId accountId:userId];
//            tableArray = self.ManagersArray;
//            NSLog(@"Contacts count = %lu,Managers count = %lu,SosContacts count = %lu",(unsigned long)self.ContactsArray.count,(unsigned long)self.ManagersArray.count,self.SosContactsArray.count);
//            
//            [loadingView stopAnimating];
//            [tableView reloadData];
//
//        }
//        else
//        {
//            [LeoMsg showMsg:@"加载管理成员失败!"];
//            [LeoMsg showMsg:description];
//        }
//    }];
    /*[self.syncManager getBoundUsers:watchId completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        
    }];*///by yan
    self.ManagersArray = [self.dataManager getManagerLists:watchId accountId:userId];
    self.ManagersArray=[self changeLocationFromManagers_2:self.ManagersArray];
    tableArray = self.ManagersArray;
    NSLog(@"Contacts count = %lu,Managers count = %lu,SosContacts count = %lu",(unsigned long)self.ContactsArray.count,(unsigned long)self.ManagersArray.count,self.SosContactsArray.count);
    
}
//调整位置，将用户调至第一
- (NSArray *)changeLocationFromManagers:(NSArray*)originManagers;
{
    NSMutableArray *managers=[[NSMutableArray alloc]initWithArray:originManagers];
    User *user=[User sharedSingleton];

    for (int i=0;i<managers.count;i++)
    {
        if ([[managers objectAtIndex:i] isKindOfClass:[Manager class]])
        {
            Manager *manager=[managers objectAtIndex:i];
            if(user!=NULL&&[user.uid isEqualToString:manager.user_id])
            {
                if ([[managers objectAtIndex:0] isKindOfClass:[Manager class]])
                {
                    Manager *bridge=[managers objectAtIndex:0];
                    [managers replaceObjectAtIndex:0 withObject:manager];
                    [managers replaceObjectAtIndex:i withObject:bridge];
                }
                else
                {
                    Contact *bridge=[managers objectAtIndex:0];
                    [managers replaceObjectAtIndex:0 withObject:manager];
                    [managers replaceObjectAtIndex:i withObject:bridge];
                }
                
            }

        }
        else
        {
            Contact *contact=[managers objectAtIndex:i];
            if(user!=NULL&&[user.uid isEqualToString:contact.user_id])
            {
                if ([[managers objectAtIndex:0] isKindOfClass:[Manager class]])
                {
                    Manager *bridge=[managers objectAtIndex:0];
                    [managers replaceObjectAtIndex:0 withObject:contact];
                    [managers replaceObjectAtIndex:i withObject:bridge];
                }
                else
                {
                    Contact *bridge=[managers objectAtIndex:0];
                    [managers replaceObjectAtIndex:0 withObject:contact];
                    [managers replaceObjectAtIndex:i withObject:bridge];
                }
                
            }
 
        }
        
    }
    return managers;
}
//调整位置，将用户调至第一，并且保证主管理员在第二位
- (NSArray *)changeLocationFromManagers_2:(NSArray*)originManagers;
{
    NSMutableArray *managers=[[NSMutableArray alloc]initWithArray:originManagers];
    NSMutableArray *newManagers=[[NSMutableArray alloc]init];
    User *user=[User sharedSingleton];
    int k=0;
    for (int i=0;managers!=NULL&& i<managers.count;i++)
    {
        if ([managers objectAtIndex:i]!=NULL&&[[managers objectAtIndex:i] isKindOfClass:[Manager class]])
        {
            Manager *manager=[managers objectAtIndex:i];
            if(user!=NULL&&user.uid!=NULL&&manager.user_id!=NULL&&[manager.user_id isEqualToString:[NSString stringWithFormat:@"%@",user.uid]])
            {
                k=i;
            }
            
        }
        else
        {
            Contact *contact=[managers objectAtIndex:i];
            if(user!=NULL&&user.uid!=NULL&&contact.user_id!=NULL&&[contact.user_id isEqualToString:[NSString stringWithFormat:@"%@",user.uid]])
            {
                 k=i;
            }
            
        }
        
    }
    [newManagers addObject:[managers objectAtIndex:k]];
    for (int i=0;i<managers.count;i++)
    {
        if (i!=k)
        {
          [newManagers addObject:[managers objectAtIndex:i]];
        }
        
    }
    return newManagers;
}

- (void)initNavButton {
    [navLeftButton setTarget:self];
    [navLeftButton setAction:@selector(back)];
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
    //[self dismissViewControllerAnimated:YES completion:nil];
}

- (void)initColorParam{
    ButtonTextNormalcolor = [UIColor colorWithRed:142.0/255 green:142.0/255 blue:147.0/255 alpha:1];
    ButtonTextHighLightcolor = [UIColor colorWithRed:71.0/255 green:178.0/255 blue:247.0/255 alpha:1];
}

//init the width for all size screen



-(void)worktable{
    self.automaticallyAdjustsScrollViewInsets=NO;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.delegate=self;
    tableView.dataSource=self;
    
    UINib *cellMember = [UINib nibWithNibName:@"MemberListTableCellTableViewCell" bundle:nil];
    [tableView registerNib:cellMember forCellReuseIdentifier:@"memberlisttablecell"];
    self.memberListTableCellTableViewCell  = [tableView dequeueReusableCellWithIdentifier:@"memberlisttablecell"];
    
    UINib *cellAdd = [UINib nibWithNibName:@"AddSafeAreaTableViewCell" bundle:nil];
    [tableView registerNib:cellAdd forCellReuseIdentifier:@"addSafeAreaCell"];
    self.addSafeAreaTableViewCell  = [tableView dequeueReusableCellWithIdentifier:@"addSafeAreaCell"];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    CGRect rect = [UIScreen mainScreen].bounds;
    
    
        if (80 * (tableArray.count) < rect.size.height) {
            tableViewHeight.constant = 80 * (tableArray.count);
        }
        else
            tableViewHeight.constant = rect.size.height - 80;
        AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
        if ((myDelegate.isAdmin)&&(tableArray.count<10)){return tableArray.count+1;}
    
        return tableArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if((indexPath.row == tableArray.count)){
        AddSafeAreaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"addSafeAreaCell"];
        cell.navController=self.navigationController;
        cell=[self addCellLine:cell forIndex:indexPath.row];
        return cell;
    }

    
    
    MemberListTableCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"memberlisttablecell"];
        cell.navController=self.navigationController;
        [cell setIsManager: YES];
        //cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (tableArray.count<=indexPath.row)
        {
            return nil;
        }
        cell = [cell getandSetDataWithManager:[tableArray objectAtIndex:indexPath.row]Type:1];
        cell=[self addCellLine:cell forIndex:indexPath.row];
        return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    
    if((indexPath.row == tableArray.count)){
        InviteViewController *addViceManagerViewController = [[InviteViewController alloc]init];
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:addViceManagerViewController animated:YES];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        return;
    }

    
    ModifyManagerViewController *modifyManagerViewController = [[ModifyManagerViewController alloc]init];
        self.hidesBottomBarWhenPushed = YES;
    modifyManagerViewController.managersArray=[tableArray objectAtIndex:indexPath.row];
       
        [self.navigationController pushViewController:modifyManagerViewController animated:YES];
    
}

-(UITableViewCell *)addCellLine:(UITableViewCell *)cell forIndex:(int)index
{
    UILabel *line;
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    if ((myDelegate.isAdmin==YES)&&(index==tableArray.count))
    {
        NSLog(@"有最后一条！");
        line=[[UILabel alloc]initWithFrame:CGRectMake(0, cell.frame.size.height-1, [UIScreen mainScreen].bounds.size.width-0, 1)];
    }
    else
    {
        if ((myDelegate.isAdmin==NO)&&(index==tableArray.count-1))
        {
            NSLog(@"有最后一条！");
            line=[[UILabel alloc]initWithFrame:CGRectMake(0, cell.frame.size.height-1, [UIScreen mainScreen].bounds.size.width-0, 1)];
        }
        else{

            line=[[UILabel alloc]initWithFrame:CGRectMake(20, cell.frame.size.height-1, [UIScreen mainScreen].bounds.size.width-20, 1)];
        }
    }
    line.backgroundColor=[UIColor colorWithRed:226/255.0 green:226/255.0 blue:228/255.0 alpha:1.0];
    
    [cell addSubview:line];
    
    return cell;
}

-(void)registerObservers
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:USERINFOUPDATE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:WATCHPHOTOUPDATE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:MANAGERPHOTOUPDATE object:nil];
}
-(void)removeObservers
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:USERINFOUPDATE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:WATCHPHOTOUPDATE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MANAGERPHOTOUPDATE object:nil];
}

- (void)receiveNotification:(NSNotification *)sender {
   
    if([sender.name isEqualToString:USERINFOUPDATE])
    {
        [self initData];
        [self.tableView reloadData];
    }
    else if([sender.name isEqualToString:WATCHPHOTOUPDATE])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self initData];
            [self.tableView reloadData];
        });
        
    }
    else if([sender.name isEqualToString:MANAGERPHOTOUPDATE])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self initData];
            [self.tableView reloadData];
        });
        
    }
    
}




@end
